﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using System.Linq;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    /// <summary>
    /// 切换入库模式
    /// </summary>
    public class PconMsgParse_InMode : PconMsgParseBase
    {
        public override void Deal(PconDto pconDto, PconPlc pconPlc)
        {
            // 有货时或已经是入库模式无法切换
            if (pconDto.WorkType == 1)
            {
                _logger.AddWcsRunLog("device", $"{pconDto.DeviceName}切换入库模式失败，已经是入库模式");
                RejectChangeMode(pconDto, 6);
                return;
            }

            var isGoods = pconDto.Machine.Pcons.Any(x => x.IsGoods == 1);
            if (isGoods)
            {
                _logger.AddWcsRunLog("device", $"{pconDto.DeviceName}切换入库模式失败，线体有载荷");
                RejectChangeMode(pconDto, 7);
                return;
            }

            // 有目的地为此且正在执行的任务时无法切换
            var isTask = _wcsDbContext.SubTasks.Any(x => x.ToLoc == pconDto.MachineName
            && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString());
            if (isTask)
            {
                _logger.AddWcsRunLog("device", $"{pconDto.DeviceName}切换入库模式失败，存在堆垛机正在搬送的任务");
                RejectChangeMode(pconDto, 8);
                return;
            }

            var pconSendMsg = new PconSendMsg()
            {
                PconName = (ushort)pconDto.PconName,
                Request = (ushort)EnumPconSendMsg.ChangeInModeCmd
            };

            InsertMsgQueue(new DeviceMsgQueueDto(pconDto, pconSendMsg));

            _mesCommunicateService.MachineModeChangeRequest(pconDto, "IN");
            _logger.AddWcsRunLog("device", $"{pconDto.DeviceName}向MES发送切换入库模式请求");
        }

        public override EnumPconPlcRequest RequestType => EnumPconPlcRequest.InMode;
        private readonly ILoggerService _logger;

        public PconMsgParse_InMode(ILoggerService logger, IMapper mapper, WcsDbContext wcsDbContext, IMesCommunicateService mesCommunicateService)
            : base(mesCommunicateService, wcsDbContext, mapper)
        {
            _logger = logger;
        }
    }
}
